package JPetStore.web.servlet;

import JPetStore.domain.Account;
import JPetStore.domain.Cart;
import JPetStore.domain.LineItem;
import JPetStore.domain.Order;
import JPetStore.persistence.LineItemDao;
import JPetStore.persistence.OrderDao;
import JPetStore.persistence.impl.LineItemDaoImpl;
import JPetStore.persistence.impl.OrderDaoImpl;
import JPetStore.service.LogService;
import JPetStore.service.OrderService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.text.View;
import java.io.IOException;
import java.util.List;

public class ViewOrderServlet extends HttpServlet {
    private static final String VIEWORDER = "/WEB-INF/jsp/order/ViewOrder.jsp";
    private static final String ERROR = "/WEB-INF/jsp/common/error.jsp";
    private Order order;
    private OrderService orderService;
    private Cart cart;

    public ViewOrderServlet() {
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        Account account = (Account)session.getAttribute("loginAccount");
        orderService = new OrderService();
        int orderID = -1;
        orderID = Integer.parseInt(request.getParameter("orderId"));
        System.out.println(orderID);
        if(orderID!=-1) {
            Order checkOrder = orderService.getOrder(orderID);
            System.out.println(checkOrder.getLineItems().size());
            Order originOrder = (Order) session.getAttribute("order");
            session.setAttribute("order", checkOrder);
            request.getRequestDispatcher(VIEWORDER).forward(request, response);
            session.setAttribute("order", originOrder);
            if (account != null) {
                String username = account.getUsername();
                String strBackUrl = "http://" + request.getServerName() + ":" + request.getServerPort()
                        + request.getContextPath() + request.getServletPath() + "?" + (request.getQueryString());
                LogService logService = new LogService();
                String logInfo = logService.logInfo(new Object[]{" "}) + strBackUrl + "查看了订单";
                logService.insertLogInfo(username, logInfo);
            }
        }
        else
        {
            session.setAttribute("message", "An error occurred processing your order (order was null).");
            request.getRequestDispatcher(ERROR).forward(request, response);
        }

    }
}
